from flask.views import MethodView
from flask import jsonify, abort
from flask import request,g
from ext import db
from flask import current_app


#模型类
from . import models
#公共资源
from util.public import set_password,check_password
from util.model_exchange import model_to_dict #模型转字典
from util.model_exchange import model_to_dict_list #查询集转列表
#认证相关
from authen.token import jwt_encode_token,authen_admin_required_middle
from util.thread_class import UserModelThread

class ThreadUserModelView(MethodView):
    def post(self):
        data = request.json
        t = UserModelThread(data)
        t.start()
        print('okok')
        return jsonify({'code':200,'msg':'okok'})

class TestLog(MethodView):
    def get(self):
        current_app.logger.error('知识就是力量')
        return jsonify({'code':200})
    def post(self):
        # Do something with the received order
        ssss
        # 1/0
        raise Exception('Order processing failed: Raised by Developer')

class TestException(MethodView):
    def get(self):
        raise Exception('test exception is ok')


class LoginView(MethodView):
    def post(self):
        print('登录成功')
        account = request.form.get('account')
        password = request.form.get('password')
        obj = models.UserModel.query.filter_by(account=account).first()
        if check_password(password=password,pwhash=obj.password):
            token = jwt_encode_token(obj.id)
            response = jsonify({'code':200,'msg':'登录成功','token':token})
            response.set_cookie('token',token)
            return response
        else:
            return jsonify({'code':400,'msg':'用户名或密码错误'})

class RoleView(MethodView):
    # decorators = (login_required,)
    def get(self):
        objs = models.RoleModel.query.all()
        print(request.__dict__)
        print(g.__dict__)
        lis = []
        for obj in objs:
            lis.append({'id':obj.id,'name':obj.name})
        return jsonify({'code':200,'data':lis})
    @authen_admin_required_middle
    # @authen_admin_required
    def post(self):
        print(request.__dict__)
        print(g.__dict__)
        name = request.form.get('name')
        if not name:
            return jsonify({'code':400,'error':'请携带上权限名'})

        obj = models.RoleModel.query.filter_by(name=name).first()
        if obj:
            return jsonify({'code':400,'error':f'{name} 权限已经存在了'})
        else:
            obj = models.RoleModel()
            obj.name=name
            db.session.add(obj)
            db.session.commit()
            return jsonify({'code':200,'msg':f'新增角色：{name} 成功'})

class RegisterView(MethodView):
    @authen_admin_required_middle
    def post(self):
        name = request.form.get('name')
        account = request.form.get('account')
        password = request.form.get('password')
        gender = request.form.get('gender')
        age = request.form.get('age')
        if not name:
            return jsonify({'code':400,'msg':'没有携带姓名'})
        if not account:
            return jsonify({'code':400,'msg':'没有携带账户'})
        if not password:
            return jsonify({'code':400,'msg':'没有携带密码'})
        if not gender:
            return jsonify({'code':400,'msg':'没有携带性别'})
        if not age:
            return jsonify({'code':400,'msg':'没有携带年龄'})
        password = set_password(password)
        obj = models.UserModel.query.filter_by(account=account).first()
        if obj:
            return jsonify({'code':400,'msg':'该账户已经在数据库中存在了'})
        else:
            obj = models.UserModel()
            obj.name=name
            obj.account=account
            obj.gender=gender
            obj.age=age
            obj.password=password
            db.session.add(obj)
            db.session.commit()
            return jsonify({'code':200,'msg':f'创建用户：{name} 成功'})

class UserView(MethodView):
    # decorators = [login_required]
    def get(self):
        '获取用户信息'
        users = models.UserModel.query.all()
        lis  = model_to_dict_list(users,['id','name','password'])
        return jsonify({'code':200,'msg':'成功','data':lis})
    @authen_admin_required_middle
    def post(self):
        '给用户设置权限'
        user_id = request.form.get('user_id')
        role_id = request.form.get('role_id')

        if not user_id:
            return jsonify({'code':400,'error':'请携带用户id'})
        if not  role_id:
            return jsonify({'code':400,'error':'没有携带权限id'})

        user = models.UserModel.query.filter_by(id=user_id).first()
        role = models.RoleModel.query.filter_by(id=role_id).first()
        if not user:
            return jsonify({'code':400,'error':'用户不存在'})
        if not role:
            return jsonify({'code':400,'error':'权限不存在'})

        user.role_id=role.id
        db.session.add(user)
        db.session.commit()
        db.session.close()
        return jsonify({'code':200,'msg':'用户设置权限成功'})